package com.llb666.e.shop.infracore.interceptor;

import com.alibaba.fastjson2.JSONObject;
import com.llb666.e.shop.infracore.config.RedisOperator;
import com.llb666.e.shop.infracore.web.BaseResponse;
import com.llb666.e.shop.infracore.web.DataResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/**
 * 用户拦截器.
 *
 * @author 斌~
 * @version 1.0
 * @date 2020/10/22 12:57 上午
 */
@Slf4j
public class UserTokenInterceptor implements HandlerInterceptor {

    public static final String REDIS_USER_TOKEN = "redis_user_token";

    @Autowired
    private RedisOperator redisOperator;

    /**
     * 拦截请求，在访问controller之前
     *
     * @param request  请求
     * @param response 响应
     * @param handler  处理
     * @return boolean --> true:请求可以放行  false:请求被拦截，被驳回
     * @throws Exception - 异常
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        log.info("进入用户登录拦截器");

        String userId = request.getHeader("headerUserId");
        String userToken = request.getHeader("headerUserToken");
        if (StringUtils.isNotBlank(userId) && StringUtils.isNotBlank(userToken)) {
            String uniqueToken = redisOperator.get(REDIS_USER_TOKEN + ":" + userId);
            if (StringUtils.isBlank(uniqueToken)) {
                log.error("缓存数据错误：用户未登录。。。");
                returnErrorResponse(response, DataResponse.errorMsg("用户未登录。。。"));
                return false;
            } else {
                if (!uniqueToken.equals(userToken)) {
                    log.info("账号异地登录。。。");
                    returnErrorResponse(response, DataResponse.errorMsg("账号异地登录。。。"));
                    return false;
                }
            }
        } else {
            log.error("请求头参数错误：用户未登录...");
            returnErrorResponse(response, DataResponse.errorMsg("用户未登录。。。"));
            return false;
        }
        return true;
    }

    /**
     * 请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）
     *
     * @param request      请求
     * @param response     响应
     * @param handler      处理
     * @param modelAndView 视图
     * @throws Exception 异常
     */
    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {

        // do nothing
    }

    /**
     * 在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）
     *
     * @param request  请求
     * @param response 响应
     * @param handler  处理
     * @param ex       异常
     * @throws Exception 异常
     */
    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {
        // do nothing
    }

    /**
     * 拦截错误返回.
     *
     * @param response   响应
     * @param jsonResult 结果转换
     */
    public void returnErrorResponse(HttpServletResponse response, BaseResponse jsonResult) {
        OutputStream outputStream = null;
        try {
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/json");
            outputStream = response.getOutputStream();
            outputStream.write(JSONObject.toJSONString(jsonResult).getBytes(StandardCharsets.UTF_8));
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.flush();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
